package com.heima.wemedia.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private WmNewMaterialMapper wmNewMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public PageResponseResult findList(WmNewsPageReqDTO dto) {
        if (dto == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();

        queryWrapper.like(StringUtils.isNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());

        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());

        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());

        queryWrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());

        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> pageReq = new Page<WmNews>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(pageReq, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());

        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1 检查参数,封装wmnews对象
        WmNews wmNews = parseDtoToWmNewS(dto);


        // 2 保存或修改文章
        saveOrUpdateWmNews(wmNews);

        // 3 保存文章内容或封面,和素材的关联关系

        // 3.1 从文章内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        // 3.2 保存文章内容引用素材的关联关系
        saveRelativeInfo(materialUrls, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
        // 3.3 保存封面和引用素材的关联关系
        saveRelativeInfoForCover(materialUrls, wmNews, dto);
        // 判断前端传入type是否为-1
        // 需要自动生成封面规则
        // 内容图片个数小于等于2,则为单图,截图一张图
        // 内容图片大于2,则为多图,截取三张图
        //内容中没有图片,则为无图
        return null;
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult deleteNewById(Integer id) {
        if (id==null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");

        }
        WmNews wmNews = getById(id);
        if(wmNews==null){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");

        }
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED)&&wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
        CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布,不能删除");
        }
        // 去除素材和文章的关系
        wmNewMaterialMapper.deleteById(id);

        removeById(wmNews.getId());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        if (dto==null||dto.getId()==null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable==null||(!WemediaConstants.WM_NEWS_UP.equals(enable)&&
                !WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {

        List<String> images = dto.getImages();
        // 1 判断前端传入type是否为-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {

            int size = materialUrls.size();
            // 图片个数为0,设为无图
            if (size == 0) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                // 个数小于等于2,截一张图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
            } else {
                // 大于2,为多图,截图三张
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imagesToStr(images));
            }

            // 修改文章
            this.updateById(wmNews);
            if(CollectionUtils.isNotEmpty(images)){
                images.stream().map(url->url.replaceAll(webSite,"")).collect(Collectors.toList());
                saveRelativeInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
            }
        }
        // 调用保存关联关系

    }

    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        // 1 根据素材路径集合 查询素材表,得到对应的id集合
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
//                Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                        .in(WmMaterial::getUrl, materialUrls)
//                        .select(WmMaterial::getId)
//        );
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        // 2 看判断id集合的数量,是否等于素材路径的数量,不等于提示素材缺失
        if (ids.size() < materialUrls.size()) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失");
        }

        // 3 批量地插入关联关系
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(wmNews.getId());
//            wmNewsMaterial.setType(type);
//
//            wmNewMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewMaterialMapper.saveRelations(ids,wmNews.getId(),type);
    }

    //3 提取内容中所涉及的素材路径
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        return mapList.stream()
                // 集合中找到所有type为image的map
                .filter(x -> "image".equals(x.get("type")))
                // 获取map的value字段值,得到路径
                .map(x -> String.valueOf(x.get("value")))
                //替换掉路径的前缀
                .map(url -> url.replaceAll(webSite, ""))
                //将得到的素材返回路径集合
                .distinct().collect(Collectors.toList());

    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //2.1 将wmnews信息补全,上下架,创建时间,发表用户id
        wmNews.setCreatedTime(new Date());
        // 默认为上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);

        // 2.2 判断id是否为空,如果为空保存wmnews,
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            // 2.3 如果不为空修改wmnews,修改前先将素材和文章关联关系删除
            wmNewMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }


    }

    private WmNews parseDtoToWmNewS(WmNewsDTO dto) {
        // 1.1 检查内容,标题,是否登录
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章标题和内容不能为空");

        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录");

        }

        // 1.2 dto拷贝属性wmmews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        // 1.3 type:如果type为-1,暂时将wmnews中的type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // 1.4 dto中images是list,wmnews中的images是字符串,
        if (CollectionUtils.isNotEmpty(dto.getImages())) {
            wmNews.setImages(imagesToStr(dto.getImages()));
        }
        // 1.5 补全id
        wmNews.setId(user.getId());
        return wmNews;
    }

    /*
     * 将字符串集合转为字符串用逗号拼接
     * 使用流的方法*/
    private String imagesToStr(List<String> images) {
        images.stream()
                // 替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite, ""))
                //将字符串使用,拼接
                .collect(Collectors.joining(","));
        return null;
    }
}
